<template>
  <div class="wrapper">
    <!-- 城市搜索框 -->
    <div class="search-wrapper">
      <input v-model="cityName" type="text" class="search-input" placeholder="请输入城市名或拼音" />
    </div>
    <!-- 搜索对应城市时，显示的城市列表 -->
    <div class="search-content" v-show="cityName" ref="searchResultRef">
      <ul>
        <li v-for="item in searchList" :key="item.id">{{ item.name }}</li>
      </ul>
    </div>
  </div>
</template>

<script>
import BetterScroll from 'better-scroll'
export default {
  props: ['cities'],
  methods: {
    /* 加载better-scroll插件 */
    betterScroll () {
      this.scroll = new BetterScroll(this.$refs.searchResultRef, {
        movable: true,
        zoom: true
      })
    }
  },
  data () {
    return {
      /* 与input绑定，搜索框中输入的城市 */
      cityName: '',
      /* 搜索到的城市列表 */
      searchList: [],
      /* 获取频率过快影响效率 */
      // eslint-disable-next-line vue/no-reserved-keys
      _timer: null
    }
  },
  watch: {
    cityName () {
      /* 去除定时器，防止上一个定时器还未清除从而引发bug */
      if (this._timer) {
        clearTimeout(this._timer)
      }
      /* 防止抖动 */
      this._timer = setTimeout(() => {
        if (this.cityName) {
          /* 清空城市搜索列表防止之前搜索到的城市依然被显示 */
          this.searchList = []
          /* 获取城市数据 */
          for (const key in this.cities) {
            this.cities[key].forEach(value => {
              if (value.name.includes(this.cityName)) {
                this.searchList.push(value)
              }
            })
          }
          console.log(this.searchList)
          /* 没有相应城市的提示 */
          if (this.searchList.length === 0) {
            this.searchList.push({name: '没有匹配结果'})
          }
        }
      }, 50)
    },
    searchList () {
      this.$nextTick(() => {
        this.betterScroll()
      })
    }
  }
}
</script>

<style lang="stylus" scoped>
@import '~styles/varibles.styl'
.search-wrapper {
  width: 100%
  height: $headerHeight
  background-color: $bgColor
  display: flex
  justify-content: center
}
.search-input {
  box-sizing:border-box
  font-size: 0.28rem;
  width:92%
  height:80%
  padding: 0.1rem
  text-align: center
  border-radius: 3px
  color: #333
}
.search-content {
  overflow:hidden
  z-index: 1
  position: absolute
  top: 1.72rem
  left: 0
  bottom: 0
  right: 0
  background-color: #f5f5f5
}
.search-content ul li {
  font-size: 0.3rem
  line-height: 0.7rem
  padding-left: 0.2rem
  color: #666
  background-color: #fff
  border-bottom: 1px solid #f3f2f2
}
</style>
